package com.kingbook.core.executor;

import com.alibaba.fastjson.JSONArray;
import com.kingbook.common.utils.StringUtils;
import com.kingbook.core.utils.JDBCHelper;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: Bucky
 * @Date: 2019/1/2
 * @Version 1.0
 */
class JSONArrayResultSetExtractor implements ResultSetExtractor<JSONArray> {

    @Override
    public JSONArray extractData(ResultSet rs) throws SQLException, DataAccessException {
        JSONArray results = new JSONArray();
        ResultSetMetaData rsm = rs.getMetaData();
        int columnCount = rsm.getColumnCount();
        while (rs.next()) {
            Map<String, Object> map = new LinkedHashMap<String, Object>(columnCount);
            for(int i = 1 ; i <= columnCount ; i++){
                map.put(StringUtils.toCamelCase(rsm.getColumnLabel(i)), JDBCHelper.getFormatResult(rs, i));
            }
            results.add(map);
        }
        return  results ;
    }

}